package com.bjpowernode.money.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.bjpowernode.money.config.AlipayConfig;
import com.bjpowernode.money.constant.UserConstant;
import com.bjpowernode.money.model.RechargeRecord;
import com.bjpowernode.money.model.User;
import com.bjpowernode.money.service.RechargeRecordService;
import com.bjpowernode.money.utils.HttpClientUtils;
import com.bjpowernode.money.utils.YzmCodeUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/27
 */
@Controller
public class RechargeRecordController {

    @Reference(interfaceClass = RechargeRecordService.class,version = "1.0.0",timeout = 20000)
    private RechargeRecordService rechargeRecordService;

    /**
     * 1、跳转充值界面
     * @return
     */
    @GetMapping("/loan/page/toRecharge")
    public String toRecharge(){
        return "toRecharge";
    }

    /**
     * 2、支付宝支付接口
     * @return
     */
    @PostMapping("/loan/page/aliPay")
    public String aliPay(@RequestParam(name = "rechargeMoney") Double rechargeMoney,
                         Model model, HttpServletRequest request){

        User user_session = (User) request.getSession().getAttribute(UserConstant.LOGIN_USER);
        if (!ObjectUtils.allNotNull(user_session)) {
            return "redirect:/loan/page/login";
        }
        RechargeRecord rechargeRecord = new RechargeRecord();
        rechargeRecord.setRechargeDesc("投资");
        rechargeRecord.setRechargeMoney(rechargeMoney);
        rechargeRecord.setRechargeTime(new Date());
        rechargeRecord.setUid(user_session.getId());
        rechargeRecord.setRechargeStatus(0 + "");
        // 生成订单号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        rechargeRecord.setRechargeNo(sdf.format(new Date())+ YzmCodeUtils.generateYzmCode(5)+user_session.getId()+YzmCodeUtils.generateYzmCode(3));

        int num = rechargeRecordService.recharge(rechargeRecord);
        if (num == 0) {
            model.addAttribute("trade_msg", "订单生成失败");
            return "toRechargeBack";
        }

        // 调用pay模块进行支付
        model.addAttribute("rechargeRecord", rechargeRecord);
        return "toAliPay";
    }

    /**
     * 3、充值：微信支付
     * @return
     */
    @PostMapping("/loan/page/wxPay")
    public String wxPay(){
        System.out.println("------------wxPay-----------");
        return "toRecharge";
    }

    /**
     * 4、支付后回调页面
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/loan/page/payBack")
    public String payBack(HttpServletRequest request, HttpServletResponse response) throws Exception {

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {

            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            response.getWriter().println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);

            // 异步查一下交易状态 降低定时器压力
            String result = HttpClientUtils.doGet("http://localhost:8007/007-money-pay/loan/pay/queryOrder?out_trade_no=" + out_trade_no);
//            String result = HttpClientUtils.doGet("http://192.168.230.128:8007/007-money-pay/loan/pay/queryOrder?out_trade_no=" + out_trade_no);

            System.out.println("************订单状态响应值：" + result);

            // 解析异步查询到的支付状态数据
            JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("alipay_trade_query_response");
            String code = jsonObject.getString("code");
            String trade_status = jsonObject.getString("trade_status");
            if (!StringUtils.equals("10000", code)) {
                // 支付失败  后续交由定时器处理
                return null;
            }
            // 判断支付状态 对应不同结果
            // 交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
            Map<String, String> map = new HashMap<>();      // 发送短信用
            User user_session = (User) request.getSession().getAttribute(UserConstant.LOGIN_USER);
            if (StringUtils.equals("WAIT_BUYER_PAY", trade_status)) {
                // 短信通知支付
                /*map.put("appkey", "61571f734d70669ee92aa8d1cd683671-bak");
                map.put("mobile", user_session.getPhone());
                map.put("content", "感谢投资，请尽快支付");
                HttpClientUtils.doGet("https://way.jd.com/chuangxin/dxjk", map);        // 只通知不关系结果*/
                return null;
            }
            if (StringUtils.equals("TRADE_CLOSED", trade_status)) {
                // 未付款交易超时关闭，或支付完成后全额退款  支付状态改为2
                rechargeRecordService.rechargeFail(out_trade_no);
                return "redirect:/loan/page/toMyCenter";
            }
            if (StringUtils.equals("TRADE_SUCCESS", trade_status)) {
                // 交易成功
                Integer userId = null;
                if (ObjectUtils.allNotNull(user_session)) {
                     userId = user_session.getId();
                }
                Double rechargeMoney = Double.parseDouble(total_amount);
                int num = rechargeRecordService.rechargeSuccess(out_trade_no,rechargeMoney,userId);
                if (num == 0) {
                    // 短信通知 延迟到账
                }
                return "redirect:/loan/page/toMyCenter";
            }

        }else {
            response.getWriter().println("验签失败");
        }
        return "redirect:/loan/page/toMyCenter";
    }

    /**
     *  5、交易关闭：根据充值记录id关闭充值
     * @param id
     * @return
     */
    @GetMapping("/loan/page/payClose")
    public String payClose(@RequestParam(name = "id",required = true)Integer id) throws Exception {
        RechargeRecord rechargeRecord = rechargeRecordService.queryById(id);
        String rechargeNo = rechargeRecord.getRechargeNo();
        String result = HttpClientUtils.doGet("http://localhost:8007/007-money-pay/loan/pay/payClose?out_trade_no=" + rechargeNo);
//        String result = HttpClientUtils.doGet("http://192.168.230.128:8007/007-money-pay/loan/pay/payClose?out_trade_no=" + rechargeNo);
        System.out.println("************交易关闭响应值："+result);
        return "redirect:/loan/page/toMyCenter";
    }

    /**
     * 6、退款：
     * @return
     */
    @GetMapping("/loan/page/payRefund")
    public String payRefund(@RequestParam(name = "out_trade_no",required = true)String out_trade_no,
                            @RequestParam(name = "refund_amount",required = true)String refund_amount,
                            @RequestParam(name = "refund_reason",required = true)String refund_reason) throws Exception {
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("out_trade_no", out_trade_no);
        paramsMap.put("refund_amount", refund_amount);
        paramsMap.put("refund_reason", refund_reason);
        String result = HttpClientUtils.doPost("http://localhost:8007/007-money-pay/loan/pay/payRefund",paramsMap);
//        String result = HttpClientUtils.doPost("http://192.168.230.128:8007/007-money-pay/loan/pay/payRefund",paramsMap);
        System.out.println("************退款响应值："+result);
        // TODO：判断响应值
        return "redirect:/loan/page/toMyCenter";
    }

}
